import express from 'express'
import mongoose from 'mongoose';
import cors from 'cors'

// 加载.env环境变量
require('dotenv-safe').config();

import { Car, CarStatus } from './entity/Car';
import { ResponseCode } from './http/model';

const main = async () => {
    await mongoose.connect(process.env.MONGODB_URL, {
        useNewUrlParser: true,
        useUnifiedTopology: true,
        useFindAndModify: false,
        useCreateIndex: true,
        // The logging level (error/warn/info/debug)
        loggerLevel: 'debug'
    })

    const app = express()
    app.use(cors({ origin: process.env.CORS_ORIGIN, credentials: true }));
    app.use(express.json());

    // 查询所有车辆
    app.get('/api/v1/cars', async (_req, res) => {
        const cars = await Car.find().sort({ _id: -1 });
        res.send({
            code: ResponseCode.SUCCESS,
            message: '',
            result: cars
        })
    })

    // 创建一些辆车
    app.post('/api/v1/car', async (_req, res) => {
        for (let index = 0; index < 10; index++) {
            await Car.create({
                car: {
                    status: CarStatus.LOCKED,
                    position: {
                        latitude: 30,
                        longitude: 120
                    }
                }
            });
        }
        res.send({})
        // res.send({
        //     code: ResponseCode.SUCCESS,
        //     message: '创建成功',
        //     result: null
        // })
    })

    app.listen(parseInt(process.env.PORT), () => {
        console.log(`listening on localhost:${process.env.PORT}`)
    })
}

main();
